//
//  TTCoreMisc.m
//  Tint
//
//  Created by Kevin Wu on 2/22/12.
//  Copyright (c) 2012 Telligenty. All rights reserved.
//

#import "TTCoreMisc.h"



#pragma mark - Launch times

BOOL TTIsFirstLaunch(void) {
    return (TTLaunchTimes() == 0);
}

NSUInteger TTLaunchTimes(void) {
    return [[NSUserDefaults standardUserDefaults] integerForKey:@"TTLaunchTimesKey"];
}

void TTIncreaseLaunchTimes(void) {
    NSUInteger times = [[NSUserDefaults standardUserDefaults] integerForKey:@"TTLaunchTimesKey"];
    [[NSUserDefaults standardUserDefaults] setInteger:times+1 forKey:@"TTLaunchTimesKey"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}



#pragma mark - Comparing number

//1.987654321 == 1.987654322
// 1.98765431 != 1.98765432
BOOL TTIsFloatEqualToFloat(CGFloat fa, CGFloat fb) {
    return (fabs(fa - fb) < (1.0E-8));
}

BOOL TTIsBoolEqualToBool(BOOL ba, BOOL bb) {
    return ( (ba && bb) || (!ba && !bb) );
}



#pragma mark - Bounding number

CGFloat TTBoundFloat(CGFloat value, CGFloat min, CGFloat max) {
    if (max < min) max = min;
    
    CGFloat bounded = value;
    if (bounded > max) bounded = max;
    if (bounded < min) bounded = min;
    return bounded;
}

NSInteger TTBoundInteger(NSInteger value, NSInteger min, NSInteger max) {
    if (max < min) max = min;
    
    NSInteger bounded = value;
    if (bounded > max) bounded = max;
    if (bounded < min) bounded = min;
    return bounded;
}



#pragma mark - Random number

NSInteger TTRandBetweenInteger(NSInteger min, NSInteger max) {
    if (min < max) {
        NSInteger range = max - min;
        return arc4random() % range + min;
    } else if (min == max) {
        return min;
    }
    return 0;
}

CGFloat TTRandBetweenFloat(CGFloat min, CGFloat max) {
    if (min < max) {
        CGFloat range = max - min;
        NSInteger rand = arc4random() % 100;
        return min + range * (rand / 100.0);
    } else if (TTIsFloatEqualToFloat(min, max)) {
        return min;
    }
    return 0.0;
}
